package Server;

import ServerOutput.Output;
import ServerOutput.OutputManager;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;


public class HttpRequest implements Runnable {
    
    Socket connectionSocket;
    BufferedReader inputReader;
    DataOutputStream outputStream;
    OutputManager outputManagerObj;
    
    public HttpRequest(Socket s, OutputManager outputMngr) throws IOException {
        connectionSocket = s;
        outputManagerObj = outputMngr;
        inputReader = new BufferedReader(new InputStreamReader(s.getInputStream()));
        outputStream = new DataOutputStream(s.getOutputStream());
    }

    @Override
    public void run() {
        try {
            processHttpRequest();
            connectionSocket.close();
            inputReader.close();
            outputStream.close();
            
        } catch (Exception ex) {
            try {
                connectionSocket.close();
                inputReader.close();
                outputStream.close();
            } catch (IOException ex1) {}
        }
    }
    
    private void processHttpRequest() throws IOException, Exception {
        /*  requestParams[0] - metodas GET/POST ar pan
         *  requestParams[1] - norimas kelias
         *  requestParams[2] - http versija
         */
        String firstLine = inputReader.readLine();
        if(firstLine == null) {
            outputStream.writeBytes(Server.constructHttpHeader(Server.ReturnCodes.INTERNAL_SERVER_ERROR_500, Server.FileTypes.none));
            return;
        }
        
        String requestParams[] = firstLine.split(" ");
        if(requestParams.length < 2) {
            outputStream.writeBytes(Server.constructHttpHeader(Server.ReturnCodes.INTERNAL_SERVER_ERROR_500, Server.FileTypes.none));
            return;
        }
        
        Output out = outputManagerObj.getOutput(requestParams[1]);
        
        String header = Server.constructHttpHeader(out.getReturnCode(), out.getFileType());
        
        outputStream.writeBytes(header);
        
        if(!out.isStreamedOutput()) {
            outputStream.writeBytes(out.getBytes());
        } else {
            DataInputStream dis = out.getDataInputStream();
            try {
                while(dis.available() != 0) {
                    byte[] b = new byte[dis.available()];
                    dis.read(b);
                    outputStream.write(b);
                }
                dis.close();
            } catch (Exception e) {
            }
        }
    }
}
